package util

import (
	"fmt"
	"runtime"
	"time"

	"kafka/idl/exterr"

	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

var debugFlag = "[DEBUG]"

// DEBUG 调试
func DEBUG(i ...interface{}) {
	now := time.Now().Format("2006-01-02 15:04:05")
	_, file, line, _ := runtime.Caller(1)
	fmt.Printf("\n%s %s [BEGIN] @%s:%d \n", now, debugFlag, file, line)
	fmt.Printf("%s %s [DATA]:%+v ", now, debugFlag, i)
	fmt.Printf("\n%s %s [END]   @%s:%d \n", now, debugFlag, file, line)
}

func IsGrpcError(err error) bool {
	if status.Code(err) == codes.Unknown {
		return false
	}
	return true
}

func GenOuterErrno(err error) int64 {
	if err == nil {
		return exterr.E_ErrOk
	}

	errno := exterr.E_DEFAULT_ERROR

	type coder interface {
		Code() int64
	}

	if code, ok := err.(coder); ok {
		errno = code.Code()
	}

	return errno
}

func GenOuterErrmsg(err error) string {
	if err == nil {
		return exterr.Msg[exterr.E_ErrOk]
	}

	errmsg, _ := exterr.Msg[GenOuterErrno(err)]

	return errmsg
}
